package com.elysia.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.elysia.common.Constants;

import com.elysia.entity.Menu;
import com.elysia.exception.ServiceException;
import com.elysia.mapper.RoleMapper;
import com.elysia.mapper.RoleMenuMapper;
import com.elysia.mapper.UserMapper;
import com.elysia.entity.User;
import com.elysia.entity.dto.UserDto;
import com.elysia.service.IMenuService;
import com.elysia.service.IUserService;
import com.elysia.utils.TokenUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private IMenuService menuService;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private RoleMenuMapper roleMenuMapper;


    /**
     * 登陆校验
     *
     * @param userDto
     * @return
     */
    @Override
    public UserDto login(UserDto userDto) {
        User one = getUserInfo(userDto);
        if (one != null) {
            BeanUtil.copyProperties(one, userDto, true);
//            // 设置token
            String token = TokenUtils.genToken(one.getId().toString(),one.getPassword());
            userDto.setToken(token);

            //查询用户的角色信息
            String role = one.getRole();//这里类似得到了ROLE_ADMIN
            List<Menu> roleMenus = getRoleMenus(role);

            userDto.setMenus(roleMenus);

            return userDto;
        } else {
            throw new ServiceException(Constants.CODE_601, "用户名或密码错误");
        }
    }

    /**
     * 分页查询
     * @param page 页数
     * @param username 用户名
     * @param email 邮箱
     * @param address 地址
     * @return
     */
    @Override
    public Page<User> findPage(Page<User> page, String username, String email, String address) {
        return userMapper.findPage(page, username, email, address);
    }


    /**
     * 获得用户信息
     * @param userDto
     * @return
     */
    private User getUserInfo(UserDto userDto) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userDto.getUsername());
        queryWrapper.eq("password", userDto.getPassword());
        User one;
        try {
            one = getOne(queryWrapper); // 从数据库查询用户信息
        } catch (Exception e) {
            throw new ServiceException(Constants.CODE_600, "系统错误");
        }
        return one;
    }


    /**
     * 注册
     * @param userDto
     * @return
     */
    @Override
    public User register(UserDto userDto) {
        User one = getUserInfo(userDto);
        if (one == null){
            one = new User();
            BeanUtil.copyProperties(userDto, one, true);
            // 默认一个普通用户的角色
            save(one);
        } else {
            throw new ServiceException(Constants.CODE_601,"用户已存在");
        }
        return one;
    }

    /**
     * 获取当前角色的菜单列表
     * @param roleFlag
     * @return
     */
    private List<Menu> getRoleMenus(String roleFlag){
        Integer roleId = roleMapper.selectByFlag(roleFlag);
        //当前角色的所有菜单id集合
        List<Integer> menuIds = roleMenuMapper.selectByRoleId(roleId);
        //查出系统所有菜单
        List<Menu> menus = menuService.findMenus("");

        //new一个最后筛选完成之后的List
        List<Menu> roleMenus = new ArrayList<>();

        // 筛选当前用户角色菜单
        for (Menu menu : menus) {
            //查看主菜单是否包含菜单id，如果没有就添加进去
            if(menuIds.contains(menu.getId())){
                roleMenus.add(menu);
            }
            //查询子菜单，把不包含的子菜单id给去除
            List<Menu> children = menu.getChildren();
            //removeIf 移除children 里边不在menuIds集合中的元素
            children.removeIf(child -> !menuIds.contains(child.getId()));
        }
        return roleMenus;
    }

}


/**
 * 作废代码
 */
//    @Autowired
//    private UserMapper userMapper;
//
//
//
//    //修改
//    public int update(User user) {
//            return userMapper.update(user);
//    }
//
//    public Integer add(User user) {
//        return userMapper.add(user);
//    }
//
//    public Integer deleteById(Integer id) {
//        return userMapper.deleteById(id);
//    }
//
//    public void findPage(Integer pageNum, Integer pageSize) {
//
//    }
//
//    public List<User> selectPage(Integer pageNum, Integer pageSize,String username) {
//        return userMapper.findPage(pageNum,pageSize,username);
//    }
//
//    public Integer selectTotal(String username) {
//        return userMapper.selectTotal(username);
//    }

